<!DOCTYPE html>
<head>
<meta charset="utf-8">
  <meta name="author" content="Arnaud Bailly - Cédric Pineau" />
  <title>Functional Programming for Simpler Design</title>
  <style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
  margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; background-color: #f8f8f8; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
pre, code { background-color: #f8f8f8; }
code > span.kw { color: #204a87; font-weight: bold; }
code > span.dt { color: #204a87; }
code > span.dv { color: #0000cf; }
code > span.bn { color: #0000cf; }
code > span.fl { color: #0000cf; }
code > span.ch { color: #4e9a06; }
code > span.st { color: #4e9a06; }
code > span.co { color: #8f5902; font-style: italic; }
code > span.ot { color: #8f5902; }
code > span.al { color: #ef2929; }
code > span.fu { color: #000000; }
code > span.er { font-weight: bold; }
  </style>
  <link rel="stylesheet" href="slides.css" />
</head>
<body>
<section>
  <h1 class="title">Functional Programming for Simpler Design</h1>
  <h2 class="author">Arnaud Bailly - Cédric Pineau</h2>
  <h3 class="date">2012-11</h3>
</section>
<section class="titleslide slide level1" id="simple-design"><h1>Simple Design</h1></section><section class="slide level2" id="ce-qui-se-conçoit-bien...">
<h1>Ce qui se conçoit bien...</h1>
<figure>
<img src="figures/platonic-solids.jpg"><figcaption></figcaption>
</figure>
</section><section class="slide level2" id="roots-of-agile">
<h1>Roots of Agile</h1>
<ul>
<li><p>http://agilemanifesto.org</p>
<blockquote>
<p>Simplicity - the art of maximizing the amount of work not done - is essential.</p>
</blockquote></li>
<li><p><strong>Simple Design</strong>: One of the 12 core practices of eXtremeProgramming</p></li>
</ul>
</section><section class="slide level2" id="what-xp-says">
<h1>What XP Says</h1>
<ul>
<li><p>Runs all the tests.</p>
<blockquote>
<p>Easily Testable</p>
</blockquote></li>
<li><p>Expresses every idea that we need to express.</p>
<blockquote>
<p>Expressive, Legible</p>
</blockquote></li>
<li><p>Says everything Once And Only Once.</p>
<blockquote>
<p>Concise</p>
</blockquote></li>
<li><p>Has no superfluous parts</p>
<blockquote>
<p>Precise</p>
</blockquote></li>
</ul>
</section><section class="slide level2" id="yet-another-definition">
<h1>Yet Another Definition</h1>
<ul>
<li>Runs all the tests.</li>
<li>Maximizes Cohesion</li>
<li>Minimizes Coupling</li>
<li>Says everything Once And Only Once</li>
</ul>
</section><section class="slide level2" id="which-tools-do-we-have">
<h1>Which Tools Do We Have?</h1>
<ul>
<li>IDEs and Development Tools</li>
<li>Frameworks</li>
<li>Design Patterns</li>
<li>Programming Languages</li>
<li>Programming Paradigms</li>
</ul>
</section><section class="slide level2" id="imperative-vs.-declarative">
<h1>Imperative vs. Declarative</h1>
<p>Two Main Paradigms:</p>
<ul>
<li><strong>Imperative</strong> (object-oriented, structured programming, parallel programming): Express directly the operations modifying the state of the world</li>
<li><strong>Declarative</strong> (<em>functional</em>, logic, data-flow): Expresses the <em>expected result</em> and let the runtime system produce it</li>
</ul>
</section><section class="slide level2" id="and-the-winner-is...">
<h1>And the Winner Is...</h1>
<p>The <strong>Imperative Programming Model!</strong></p>
<ul>
<li>Appears more &quot;obvious&quot;, more immediate, one directly &quot;talks to the machine&quot;</li>
<li>Declarative programming tools are reserved for math-savvy nerds toying with abstract non-sense (read: Category theory, non-standard logic...)</li>
</ul>
</section><section class="slide level2" id="but-but-but">
<h1>But, but, but</h1>
<ul>
<li><em>Functional programming</em> is not incompatible with OO concepts</li>
<li>Imperative programming did not deliver on all its promises: Concurrency? Maintenance? Abstraction? Reuse?</li>
</ul>
</section><section class="slide level2" id="the-future-is-functional">
<h1>The Future is Functional</h1>
<p>For all these reasons, tomorrow you will be using a functional language</p>
<p>Scala, Haskell, Erlang, Clojure, Groovy, Python, F#...</p>
</section><section class="slide level2" id="the-future-is-functional-1">
<h1>The Future is Functional</h1>
<p>For all these reasons, tomorrow you will be using a functional language</p>
<p>Scala, Haskell, Erlang, Clojure, Groovy, Python, F#...</p>
<img class="overlay" src="figures/really.png">
</section><section class="slide level2" id="no-the-future-is...">
<h1>No, The Future is...</h1>
<p>Java, C#, PHP, C++...</p>
</section><section class="slide level2" id="but-differently">
<h1>But Differently!</h1>
<ul>
<li>In the Java World: Java8 &amp; JSR-355 (Lambda Expressions for the JavaTM Programming Language)</li>
</ul>
</section>
<section class="titleslide slide level1" id="purity"><h1>Purity</h1></section><section class="slide level2" id="living-your-dreams">
<h1>Living Your Dreams</h1>
<figure>
<img src="figures/unicorn.jpg"><figcaption></figcaption>
</figure>
</section><section class="slide level2" id="mathematical-functions">
<h1>Mathematical Functions</h1>
<p>More precisely, <em>total functions</em> in the mathematical sense of a relationship between 2 sets:</p>
<ul>
<li>Each element of the <em>domain</em> set has one and only one image in the <em>range</em> set</li>
<li>This image is dependent of the input only</li>
<li>Such functions are called <strong>pure</strong></li>
</ul>
</section><section class="slide level2" id="why">
<h1>Why?</h1>
<ul>
<li>Makes your life easier: No hidden variables, no side-effects</li>
<li>Makes your code more <strong>testable</strong></li>
<li>Provides <strong>idempotency</strong>: Function can be evaluated more than once</li>
<li>Makes <strong>laziness</strong> possible: Function can be evaluated only when really needed</li>
</ul>
</section><section class="slide level2" id="an-impure-function">
<h1>An impure &quot;function&quot;</h1>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> DateUtils {

  <span class="kw">private</span> HolidaysDAO holidaysDao;
  
  <span class="co">/**</span>
<span class="co">   * This function is not pure:</span>
<span class="co">   *  - It uses a side-effect to compute its result</span>
<span class="co">   */</span>
  <span class="kw">public</span> Date <span class="fu">nextOpenDay</span>(Date startDate) {
     Date result = <span class="kw">null</span>;
     List&lt;Date&gt; holidays = holidaysDao.<span class="fu">getHolidays</span>(startDate);
     <span class="co">// some length computation</span>
     <span class="kw">return</span> result;
  }</code></pre>
</section><section class="slide level2" id="same-function-side-effect-free">
<h1>Same function, Side-effect Free</h1>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> DateUtils {

  <span class="co">/**</span>
<span class="co">   * This one is pure, it only depends on its input values.</span>
<span class="co">   */</span>
  <span class="kw">public</span> Date <span class="fu">nextOpenDay</span>(Date startDate, List&lt;Date&gt; holidays) {
     Date result = <span class="kw">null</span>;
     <span class="co">// some length computation</span>
     <span class="kw">return</span> result;
  }
}</code></pre>
</section><section class="slide level2" id="caveats">
<h1>Caveats</h1>
<p>What happens if:</p>
<ul>
<li>The &quot;function&quot; modifies a Date object in the input list?</li>
<li>This list is concurrently modified by other computations?</li>
</ul>
</section>
<section class="titleslide slide level1" id="immutability"><h1>Immutability</h1></section><section class="slide level2" id="some-things-are-incorruptible">
<h1>Some Things Are Incorruptible</h1>
<figure>
<img src="figures/gold.jpg"><figcaption></figcaption>
</figure>
</section><section class="slide level2" id="referential-transparency">
<h1>Referential Transparency</h1>
<p>Once assigned a value, a reference never changes</p>
<ul>
<li>Also called <strong>referential transparency</strong>: Using references is <em>the same</em> as using values</li>
<li>This applies to all references, including fields of all objects in an object tree</li>
</ul>
</section><section class="slide level2" id="classic-mutable-object...">
<h1>Classic Mutable Object...</h1>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> User {
  <span class="kw">private</span> String email;
  <span class="kw">private</span> String firstName;
  
  <span class="kw">public</span> <span class="fu">User</span>(String email, String firstName) {
    <span class="kw">this</span>.<span class="fu">email</span> = email;
    <span class="kw">this</span>.<span class="fu">firstName</span> = firstName;
  }
  
  <span class="kw">public</span> String <span class="fu">getEmail</span>() {
    <span class="kw">return</span> email;
  }

  <span class="kw">public</span> <span class="dt">void</span> <span class="fu">setEmail</span>(String email) {
    <span class="kw">this</span>.<span class="fu">email</span> = email;
  }
}</code></pre>
</section><section class="slide level2" id="breaks-referential-transparency">
<h1>... breaks Referential Transparency</h1>
<p>Equality is not preserved which might break containers like Hashmaps.</p>
<pre class="sourceCode java"><code class="sourceCode java">  @Test
  <span class="kw">public</span> <span class="dt">void</span> <span class="fu">preservesReferentialTransparency</span> () {
     User joe = <span class="kw">new</span> <span class="fu">User</span>(<span class="st">&quot;joe@acme.com&quot;</span>,<span class="st">&quot;John&quot;</span>);
     User joe2 = <span class="kw">new</span> <span class="fu">User</span>(<span class="st">&quot;joe@acme.com&quot;</span>,<span class="st">&quot;John&quot;</span>);
     
     <span class="fu">assertThat</span>(joe).<span class="fu">isEqualTo</span>(joe2);
     
     joe2.<span class="fu">setFirstname</span>(<span class="st">&quot;Joe&quot;</span>);
     
     <span class="fu">assertThat</span>(joe).<span class="fu">isNotEqualTo</span>(joe2);
  }</code></pre>
</section><section class="slide level2" id="same-object-this-time-immutable">
<h1>Same Object, This Time Immutable</h1>
<pre class="sourceCode java"><code class="sourceCode java">@Immutable
<span class="kw">public</span> <span class="kw">class</span> User {
  <span class="kw">private</span> <span class="dt">final</span> String email;
  <span class="kw">private</span> <span class="dt">final</span> String firstName;
  
  <span class="kw">public</span> <span class="fu">User</span>(String email, String firstName) {
    <span class="kw">this</span>.<span class="fu">email</span> = email;
    <span class="kw">this</span>.<span class="fu">firstName</span> = firstName;
  }
  
  <span class="kw">public</span> String <span class="fu">getEmail</span>() {
    <span class="kw">return</span> email;
  }
}</code></pre>
</section><section class="slide level2" id="make-objects-immutable">
<h1>Make Objects Immutable</h1>
<ul>
<li>Collections can be made immutable:</li>
</ul>
<pre class="sourceCode java"><code class="sourceCode java">  Collection&lt;String&gt; names = Collections.<span class="fu">unmodifiableList</span>(listOfNames);</code></pre>
<ul>
<li>Create Immutable Data objects with Lombok</li>
</ul>
<pre class="sourceCode java"><code class="sourceCode java">@Data
<span class="kw">public</span> <span class="kw">class</span> User {
  <span class="kw">private</span> <span class="dt">final</span> String name;
  <span class="kw">private</span> <span class="dt">final</span> Email email;
}</code></pre>
</section><section class="slide level2" id="make-objects-immutable-2">
<h1>Make Objects Immutable (2)</h1>
<ul>
<li>Immutable Collections in Guava</li>
</ul>
<pre class="sourceCode java"><code class="sourceCode java">List&lt;String&gt; famousSmiths = ImmutableList.<span class="fu">builder</span>()
   .<span class="fu">add</span>(<span class="st">&quot;John Smith&quot;</span>)
   .<span class="fu">add</span>(<span class="st">&quot;Robert Smith&quot;</span>)
   .<span class="fu">add</span>(<span class="st">&quot;Patti Smith&quot;</span>)
   .<span class="fu">build</span>();</code></pre>
</section><section class="slide level2" id="immutability-can-be-efficient">
<h1>Immutability Can Be Efficient</h1>
<figure>
<img style="width: 60%; height: 60%; margin-left: 20%" src="figures/copy-on-write.png"><figcaption></figcaption>
</figure>
</section>
<section class="titleslide slide level1" id="expressivity"><h1>Expressivity</h1></section><section class="slide level2" id="choose-your-language">
<h1>Choose Your Language</h1>
<figure>
<img src="figures/babel.jpg"><figcaption></figcaption>
</figure>
</section><section class="slide level2" id="everything-is-a-first-class-value">
<h1>Everything is a First-Class Value</h1>
<ul>
<li>Functions are <em>first-class objects</em></li>
<li><em>Generic programming</em> provides write-once use-anywhere library functions</li>
<li><em>Higher-order functions</em> can take functions as input and return functions</li>
<li>Decouple <em>control flow</em> from <em>data structures</em> from <em>business rules</em></li>
</ul>
</section><section class="slide level2" id="simplifying-control-structures">
<h1>Simplifying Control Structures</h1>
<p>Return all values looked-up in a hashmap using Guava's facilities:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="dt">final</span> Map&lt;String, Object&gt; map = ...
Function&lt;String,Object&gt; lookup = <span class="kw">new</span> Function&lt;String,Object() {
   <span class="kw">public</span> Object <span class="fu">apply</span>(String name) {
     <span class="kw">return</span> map.<span class="fu">get</span>(name);
   }
}

List&lt;String&gt; names = ...
<span class="kw">return</span> Lists.<span class="fu">transform</span>(names, lookup);</code></pre>
</section>
<section class="titleslide slide level1" id="composability"><h1>Composability</h1></section><section class="slide level2" id="divide-quod-impera">
<h1>Divide Quod Impera</h1>
<figure>
<img src="figures/lego.jpg"><figcaption></figcaption>
</figure>
</section><section class="slide level2" id="composing-functions">
<h1>Composing Functions</h1>
<ul>
<li>Plain functions can be <strong>composed</strong> provided they have compatible types to produce new functions</li>
</ul>
<pre class="sourceCode java"><code class="sourceCode java">Function&lt;&gt; asInt = <span class="kw">new</span> Function&lt;&gt;() { <span class="kw">... </span>};
Function&lt;&gt; divideBy2 = <span class="kw">new</span> Function&lt;&gt;() { <span class="kw">... </span>};

Function&lt;&gt; divideString = Functions.<span class="fu">compose</span>(divideBy2, asInt);</code></pre>
</section><section class="slide level2" id="composing-functions-over-containers">
<h1>Composing Functions Over Containers</h1>
<pre class="sourceCode java"><code class="sourceCode java">ListenableFuture&lt;Integer&gt; store = <span class="co">//</span>
    <span class="fu">transform</span>( <span class="co">//</span>
        <span class="fu">transform</span>( <span class="co">//</span>
            <span class="fu">transform</span>( <span class="co">//</span>
                <span class="fu">future</span>(<span class="fu">loadDocuments</span>(slice, index)), <span class="co">//</span>
                <span class="kw">new</span> AsyncFunction&lt;Map&lt;String, Builder&gt;, Map&lt;String, Builder&gt;&gt;() {
                        <span class="kw">return</span> <span class="fu">future</span>(<span class="fu">matchDocuments</span>(input, index));
                }), <span class="co">//</span>
            <span class="kw">new</span> AsyncFunction&lt;Map&lt;String, Builder&gt;, Map&lt;String, Builder&gt;&gt;() {
                    <span class="kw">return</span> <span class="fu">future</span>(<span class="fu">classifyDocuments</span>(input));
            }), <span class="co">//</span>
        <span class="kw">new</span> AsyncFunction&lt;Map&lt;String, Builder&gt;, Integer&gt;() {
                <span class="kw">return</span> <span class="fu">future</span>(<span class="fu">storeDocuments</span>(input, index));
        });</code></pre>
</section><section class="slide level2" id="credits">
<h1>Credits</h1>
<ul>
<li><a href="http://www.aznewage.com/unicor1.jpg">Unicorn</a></li>
<li><a href="http://www.etftrends.com/wp-content/uploads/2012/01/investing-in-gold.jpg">Gold</a></li>
<li><a href="http://en.wikipedia.org/wiki/The_Tower_of_Babel_%28Bruegel%29">Babel</a></li>
<li><a href="http://1.bp.blogspot.com/-Mhb5PF-QDSc/T0YcPZ_EVzI/AAAAAAAAFxo/FjJcHYw9wo0/s1600/Lego.jpg">Lego</a></li>
</ul>
</section>
<!-- {{{{ dzslides core
#
#
#     __  __  __       .  __   ___  __
#    |  \  / /__` |    | |  \ |__  /__`
#    |__/ /_ .__/ |___ | |__/ |___ .__/ core :€
#
#
# The following block of code is not supposed to be edited.
# But if you want to change the behavior of these slides,
# feel free to hack it!
#
-->

<div id="progress-bar"></div>

<!-- Default Style -->
<style>
  * { margin: 0; padding: 0; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; }
  details { display: none; }
  body {
    width: 800px; height: 600px;
    margin-left: -400px; margin-top: -300px;
    position: absolute; top: 50%; left: 50%;
    overflow: hidden;
  }
  section {
    position: absolute;
    pointer-events: none;
    width: 100%; height: 100%;
  }
  section[aria-selected] { pointer-events: auto; }
  html { overflow: hidden; }
  body { display: none; }
  body.loaded { display: block; }
  .incremental {visibility: hidden; }
  .incremental[active] {visibility: visible; }
  #progress-bar{
    bottom: 0;
    position: absolute;
    -moz-transition: all 1.0s ease-in-out;
    -webkit-transition: width 400ms linear 0s;
    -ms-transition: width 400ms linear 0s;
    transition: width 400ms linear 0s;
  }
  figure {
    width: 100%;
    height: 100%;
  }
  figure > * {
    position: absolute;
  }
  figure > img, figure > video {
    width: 100%; height: 100%;
  }
</style>

<script>
  var Dz = {
    remoteWindows: [],
    idx: -1,
    step: 0,
    slides: null,
    progressBar : null,
    params: {
      autoplay: "1"
    }
  };

  Dz.init = function() {
    document.body.className = "loaded";
    this.slides = $$("body > section");
    this.progressBar = $("#progress-bar");
    this.setupParams();
    this.onhashchange();
    this.setupTouchEvents();
    this.onresize();
  }
  
  Dz.setupParams = function() {
    var p = window.location.search.substr(1).split('&');
    p.forEach(function(e, i, a) {
      var keyVal = e.split('=');
      Dz.params[keyVal[0]] = decodeURIComponent(keyVal[1]);
    });
  // Specific params handling
    if (!+this.params.autoplay)
      $$.forEach($$("video"), function(v){ v.controls = true });
  }

  Dz.onkeydown = function(aEvent) {
    // Don't intercept keyboard shortcuts
    if (aEvent.altKey
      || aEvent.ctrlKey
      || aEvent.metaKey
      || aEvent.shiftKey) {
      return;
    }
    if ( aEvent.keyCode == 37 // left arrow
      || aEvent.keyCode == 38 // up arrow
      || aEvent.keyCode == 33 // page up
    ) {
      aEvent.preventDefault();
      this.back();
    }
    if ( aEvent.keyCode == 39 // right arrow
      || aEvent.keyCode == 40 // down arrow
      || aEvent.keyCode == 34 // page down
    ) {
      aEvent.preventDefault();
      this.forward();
    }
    if (aEvent.keyCode == 35) { // end
      aEvent.preventDefault();
      this.goEnd();
    }
    if (aEvent.keyCode == 36) { // home
      aEvent.preventDefault();
      this.goStart();
    }
    if (aEvent.keyCode == 32) { // space
      aEvent.preventDefault();
      this.toggleContent();
    }
    if (aEvent.keyCode == 70) { // f
      aEvent.preventDefault();
      this.goFullscreen();
    }
  }

  /* Touch Events */

  Dz.setupTouchEvents = function() {
    var orgX, newX;
    var tracking = false;

    var db = document.body;
    db.addEventListener("touchstart", start.bind(this), false);
    db.addEventListener("touchmove", move.bind(this), false);

    function start(aEvent) {
      aEvent.preventDefault();
      tracking = true;
      orgX = aEvent.changedTouches[0].pageX;
    }

    function move(aEvent) {
      if (!tracking) return;
      newX = aEvent.changedTouches[0].pageX;
      if (orgX - newX > 100) {
        tracking = false;
        this.forward();
      } else {
        if (orgX - newX < -100) {
          tracking = false;
          this.back();
        }
      }
    }
  }

  /* Adapt the size of the slides to the window */

  Dz.onresize = function() {
    var db = document.body;
    var sx = db.clientWidth / window.innerWidth;
    var sy = db.clientHeight / window.innerHeight;
    var transform = "scale(" + (1/Math.max(sx, sy)) + ")";

    db.style.MozTransform = transform;
    db.style.WebkitTransform = transform;
    db.style.OTransform = transform;
    db.style.msTransform = transform;
    db.style.transform = transform;
  }


  Dz.getDetails = function(aIdx) {
    var s = $("section:nth-of-type(" + aIdx + ")");
    var d = s.$("details");
    return d ? d.innerHTML : "";
  }

  Dz.onmessage = function(aEvent) {
    var argv = aEvent.data.split(" "), argc = argv.length;
    argv.forEach(function(e, i, a) { a[i] = decodeURIComponent(e) });
    var win = aEvent.source;
    if (argv[0] === "REGISTER" && argc === 1) {
      this.remoteWindows.push(win);
      this.postMsg(win, "REGISTERED", document.title, this.slides.length);
      this.postMsg(win, "CURSOR", this.idx + "." + this.step);
      return;
    }
    if (argv[0] === "BACK" && argc === 1)
      this.back();
    if (argv[0] === "FORWARD" && argc === 1)
      this.forward();
    if (argv[0] === "START" && argc === 1)
      this.goStart();
    if (argv[0] === "END" && argc === 1)
      this.goEnd();
    if (argv[0] === "TOGGLE_CONTENT" && argc === 1)
      this.toggleContent();
    if (argv[0] === "SET_CURSOR" && argc === 2)
      window.location.hash = "#" + argv[1];
    if (argv[0] === "GET_CURSOR" && argc === 1)
      this.postMsg(win, "CURSOR", this.idx + "." + this.step);
    if (argv[0] === "GET_NOTES" && argc === 1)
      this.postMsg(win, "NOTES", this.getDetails(this.idx));
  }

  Dz.toggleContent = function() {
    // If a Video is present in this new slide, play it.
    // If a Video is present in the previous slide, stop it.
    var s = $("section[aria-selected]");
    if (s) {
      var video = s.$("video");
      if (video) {
        if (video.ended || video.paused) {
          video.play();
        } else {
          video.pause();
        }
      }
    }
  }

  Dz.setCursor = function(aIdx, aStep) {
    // If the user change the slide number in the URL bar, jump
    // to this slide.
    aStep = (aStep != 0 && typeof aStep !== "undefined") ? "." + aStep : ".0";
    window.location.hash = "#" + aIdx + aStep;
  }

  Dz.onhashchange = function() {
    var cursor = window.location.hash.split("#"),
        newidx = 1,
        newstep = 0;
    if (cursor.length == 2) {
      newidx = ~~cursor[1].split(".")[0];
      newstep = ~~cursor[1].split(".")[1];
      if (newstep > Dz.slides[newidx - 1].$$('.incremental > *').length) {
        newstep = 0;
        newidx++;
      }
    }
    this.setProgress(newidx, newstep);
    if (newidx != this.idx) {
      this.setSlide(newidx);
    }
    if (newstep != this.step) {
      this.setIncremental(newstep);
    }
    for (var i = 0; i < this.remoteWindows.length; i++) {
      this.postMsg(this.remoteWindows[i], "CURSOR", this.idx + "." + this.step);
    }
  }

  Dz.back = function() {
    if (this.idx == 1 && this.step == 0) {
      return;
    }
    if (this.step == 0) {
      this.setCursor(this.idx - 1,
                     this.slides[this.idx - 2].$$('.incremental > *').length);
    } else {
      this.setCursor(this.idx, this.step - 1);
    }
  }

  Dz.forward = function() {
    if (this.idx >= this.slides.length &&
        this.step >= this.slides[this.idx - 1].$$('.incremental > *').length) {
        return;
    }
    if (this.step >= this.slides[this.idx - 1].$$('.incremental > *').length) {
      this.setCursor(this.idx + 1, 0);
    } else {
      this.setCursor(this.idx, this.step + 1);
    }
  }

  Dz.goStart = function() {
    this.setCursor(1, 0);
  }

  Dz.goEnd = function() {
    var lastIdx = this.slides.length;
    var lastStep = this.slides[lastIdx - 1].$$('.incremental > *').length;
    this.setCursor(lastIdx, lastStep);
  }

  Dz.setSlide = function(aIdx) {
    this.idx = aIdx;
    var old = $("section[aria-selected]");
    var next = $("section:nth-of-type("+ this.idx +")");
    if (old) {
      old.removeAttribute("aria-selected");
      var video = old.$("video");
      if (video) {
        video.pause();
      }
    }
    if (next) {
      next.setAttribute("aria-selected", "true");
      var video = next.$("video");
      if (video && !!+this.params.autoplay) {
        video.play();
      }
    } else {
      // That should not happen
      this.idx = -1;
      // console.warn("Slide doesn't exist.");
    }
  }

  Dz.setIncremental = function(aStep) {
    this.step = aStep;
    var old = this.slides[this.idx - 1].$('.incremental > *[aria-selected]');
    if (old) {
      old.removeAttribute('aria-selected');
    }
    var incrementals = $$('.incremental');
    if (this.step <= 0) {
      $$.forEach(incrementals, function(aNode) {
        aNode.removeAttribute('active');
      });
      return;
    }
    var next = this.slides[this.idx - 1].$$('.incremental > *')[this.step - 1];
    if (next) {
      next.setAttribute('aria-selected', true);
      next.parentNode.setAttribute('active', true);
      var found = false;
      $$.forEach(incrementals, function(aNode) {
        if (aNode != next.parentNode)
          if (found)
            aNode.removeAttribute('active');
          else
            aNode.setAttribute('active', true);
        else
          found = true;
      });
    } else {
      setCursor(this.idx, 0);
    }
    return next;
  }

  Dz.goFullscreen = function() {
    var html = $('html'),
        requestFullscreen = html.requestFullscreen || html.requestFullScreen || html.mozRequestFullScreen || html.webkitRequestFullScreen;
    if (requestFullscreen) {
      requestFullscreen.apply(html);
    }
  }
  
  Dz.setProgress = function(aIdx, aStep) {
    var slide = $("section:nth-of-type("+ aIdx +")");
    if (!slide)
      return;
    var steps = slide.$$('.incremental > *').length + 1,
        slideSize = 100 / (this.slides.length - 1),
        stepSize = slideSize / steps;
    this.progressBar.style.width = ((aIdx - 1) * slideSize + aStep * stepSize) + '%';
  }
  
  Dz.postMsg = function(aWin, aMsg) { // [arg0, [arg1...]]
    aMsg = [aMsg];
    for (var i = 2; i < arguments.length; i++)
      aMsg.push(encodeURIComponent(arguments[i]));
    aWin.postMessage(aMsg.join(" "), "*");
  }
  
  function init() {
    Dz.init();
    window.onkeydown = Dz.onkeydown.bind(Dz);
    window.onresize = Dz.onresize.bind(Dz);
    window.onhashchange = Dz.onhashchange.bind(Dz);
    window.onmessage = Dz.onmessage.bind(Dz);
  }

  window.onload = init;
</script>


<script> // Helpers
  if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {

      // closest thing possible to the ECMAScript 5 internal IsCallable
      // function 
      if (typeof this !== "function")
      throw new TypeError(
        "Function.prototype.bind - what is trying to be fBound is not callable"
      );

      var aArgs = Array.prototype.slice.call(arguments, 1),
          fToBind = this,
          fNOP = function () {},
          fBound = function () {
            return fToBind.apply( this instanceof fNOP ? this : oThis || window,
                   aArgs.concat(Array.prototype.slice.call(arguments)));
          };

      fNOP.prototype = this.prototype;
      fBound.prototype = new fNOP();

      return fBound;
    };
  }

  var $ = (HTMLElement.prototype.$ = function(aQuery) {
    return this.querySelector(aQuery);
  }).bind(document);

  var $$ = (HTMLElement.prototype.$$ = function(aQuery) {
    return this.querySelectorAll(aQuery);
  }).bind(document);

  $$.forEach = function(nodeList, fun) {
    Array.prototype.forEach.call(nodeList, fun);
  }

</script>
<!-- vim: set fdm=marker: }}} -->
</body>
</html>
